/*
 *  Copyright 2008 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.common.util.DateUtil;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.util.core.ApplicationResources;
import com.blandware.atleap.webapp.util.core.GlobalProperties;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.SyndFeedOutput;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>Action that outputs a syndication feed that contains last news.</p>
 * <p><a href="NewsFeedAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.3 $ $Date: 2008/01/14 16:31:39 $
 * @struts.action path="/syndication/news"
 * name="newsItemForm"
 * validate="false"
 * @struts.action-forward name="showNewsArchive"
 * path="/news/showArchive"
 */
public final class NewsFeedAction extends BaseAction {

    private static final String FEED_TYPE_PARAMETER = "feedType";

    /**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        String feedType = request.getParameter(FEED_TYPE_PARAMETER);
        // if feed type is not specified, say 'not found'
        if (GenericValidator.isBlankOrNull(feedType)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }

        GlobalProperties globalProperties = GlobalProperties.getInstance(request.getSession().getServletContext());
        ApplicationResources applicationResources = ApplicationResources.getInstance(request.getSession().getServletContext());
        Integer limit = globalProperties.getInteger(WebappConstants.GLOBAL_PROPERTY_SYNDICATION_FEED_SIZE, 10);

		List roles = null;
		String userName = request.getRemoteUser();
		UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
		if ( userName != null ) {
			User user = userManager.retrieveUser(userName);
			roles = user.getRoles();
		}

		Locale locale = (Locale) request.getSession().getAttribute(Globals.LOCALE_KEY);

		Map queryParameters = new HashMap();
		queryParameters.put("localeIdentifier", locale.getLanguage());
		queryParameters.put("roles", roles);

		QueryInfo queryInfo = new QueryInfo();
		queryInfo.setQueryParameters(queryParameters);
		queryInfo.setLimit(limit);

		NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
		List newsList = newsManager.getLastNews(queryInfo);

        Date titleDate = new Date();
        if (newsList.size() > 0) {
            titleDate = ((NewsItem) newsList.get(0)).getPublicationDate();
        }
        String formattedDate = DateUtil.formatDate(titleDate, locale);

        SyndFeed feed = new SyndFeedImpl();
        String link = WebappUtil.computeURL(mapping.findForward("showNewsArchive").getPath(), null, null, null, null, request, response, false, false, true, true);
        feed.setLink(WebappUtil.computeExternalURL(link, false, request));
        feed.setTitle(applicationResources.getMessage(request, "news.feed.title",
                new Object[]{applicationResources.getMessage(request, "core.commons.webapp.name"), formattedDate}));
        feed.setDescription("");
        feed.setFeedType(feedType);

        List entries = new ArrayList(newsList.size());
		for ( ListIterator i = newsList.listIterator(); i.hasNext(); ) {
			NewsItem newsItem = (NewsItem) i.next();
            SyndEntry entry = new SyndEntryImpl();
            entry.setTitle(WebappUtil.getFieldValue(newsItem.getTitle(), locale.getLanguage(), request, true));
            SyndContent content = new SyndContentImpl();
            content.setType(Constants.MIME_TYPE_HTML);
            content.setValue(WebappUtil.getFieldValue(newsItem.getAnnotation(), locale.getLanguage(), request, true));
            entry.setDescription(content);
            entry.setPublishedDate(newsItem.getPublicationDate());
            link = WebappUtil.computeURL(newsItem.getUri(), null, null, null, null, request, response, false, false, true, true);
            entry.setLink(WebappUtil.computeExternalURL(link, false, request));
            entries.add(entry);
        }
        feed.setEntries(entries);

        response.setContentType(WebappConstants.FEED_CONTENT_TYPE);
        SyndFeedOutput output = new SyndFeedOutput();
        output.output(feed, response.getWriter());
        return null;
    }
}
